package com.coin900.coin.server.exception;

import com.coin900.coin.base.AjaxResponse;
import com.coin900.coin.server.BaseController;
import com.value.exception.BusinessException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Unibon
 * <p/>
 * Copyright (c) 2012 YouPeng ValueSoft Inc., All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of
 * ValueSoft Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ValueSoft.com.
 * <p/>
 * Revision History
 * Date      		Programmer       Notes
 * *********************************************************************
 * <p/>
 * 异常处理
 */
@Component
public class ExceptionHandler extends BaseController implements HandlerExceptionResolver {
    private static final Log logger = LogFactory.getLog(ExceptionHandler.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object o, Exception e) {
        logger.error(e.getMessage(),e);
        String errorCode = super.buildErrorCode(req);
        String msg = "系统处理异常，请联系管理员";
        if (e instanceof BusinessException){
            BusinessException exception = (BusinessException) e;
            msg = exception.getMessage();
        }
        String uri = req.getRequestURI();
        if(uri.indexOf(".json")!=-1){
            AjaxResponse response = super.buildAjaxResponse(req);
            response.addError(errorCode, msg);
            resp.setStatus(500);
            String callback = req.getParameter("callback");
            if(StringUtils.isNotBlank(callback)){
                try {
                    resp.getWriter().write(callback + "(" + JSONObject.fromObject(response.getModelMap()).toString() + ")");
                    resp.getWriter().flush();
                } catch (IOException e1) {
                    logger.error(e1.getMessage(), e1);
                }
                return null;
            }else{
                return response.getMav();
            }
        }else{
            ModelAndView view;
            if (msg.lastIndexOf("register") != -1) {
                view = new ModelAndView("project/404");
            } else {
                view = new ModelAndView("project/404");
            }
            view.addObject("errorCode", errorCode);
            view.addObject("msg",msg);
//            view.addObject("resServer", "");
            return view;
        }
    }
}
